﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;

namespace Steve
{
    [Serializable]
    [DataContract]
    public sealed class Site : AuditObject
    {
        [DataMember]
        public string SiteName { get; set; }
        [DataMember]
        public bool IsManagedSite { get; set; }

        [DataMember]
        public string Authority { get; set; }
        
        [DataMember]
        public IEnumerable<string> AlternateAuthorities { get; set; }
    }

    public static class SiteExtensions
    {
        public static Site NavigateToSite(this IEnumerable<Site> sites, Uri url)
        {
            if (url == null) throw new ArgumentNullException("url");

            return NavigateToSite(sites, url.Authority);
        }

        [SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads", Justification = "Has to go this way as scheme is unknown")]
        public static Site NavigateToSite(this IEnumerable<Site> sites, string authority)
        {
            if (sites == null) throw new ArgumentNullException("sites");
            if (string.IsNullOrEmpty(authority)) throw new ArgumentNullException("authority");

            var match = (from s in sites
                         where string.Equals(s.Authority, authority, StringComparison.OrdinalIgnoreCase)
                         select s).FirstOrDefault();

            if (match != null) return match;

            var emptyAlts = new List<string>();

            match = (from s in sites
                     let alts = s.AlternateAuthorities ?? emptyAlts
                     from alt in alts
                     where string.Equals(alt, authority, StringComparison.OrdinalIgnoreCase)
                     select s).FirstOrDefault();

            return match;
        }
    }
}
